package com.jiankangjin.transsystem.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiankangjin.common.uuid.IdGenerator;
import com.jiankangjin.trading.dao.IOrderDataDao;
import com.jiankangjin.trading.dao.IPaymentDataDao;
import com.jiankangjin.trading.entity.OrderDataEntity;
import com.jiankangjin.trading.entity.PaymentDataEntity;
import com.jiankangjin.transsystem.common.CommonResponse;
import com.jiankangjin.transsystem.common.Constant;
import com.jiankangjin.transsystem.util.StringUtil;
import com.jiankangjin.transsystem.util.TimeUtil;

/**  
 * 申请退款  
 */
@Controller
public class CreateRefundController {
	private static final Log logger = LogFactory.getLog(CreateRefundController.class);

	@Autowired
	private IOrderDataDao iOrderDataDao;
	
	@Autowired
	private IPaymentDataDao iPaymentDataDao;
	
	/**
	 * 申请退款接口  
	 */
	@RequestMapping(value="/create_refund" , method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> createRefund(
			@RequestParam(required = false) String module_id,
			@RequestParam(required = false) String version,
			@RequestParam(required = false) String sign,
			@RequestParam(required = false) String order_id,
			@RequestParam(required = false) String refund_fee,
			@RequestParam(required = false) String comment,
			@RequestParam(required = false) String operator_id,
			@RequestParam(required = false) String operator_name
			){
		StringBuilder sb = new StringBuilder();
		sb.append("module_id=" + module_id)
			.append(" version=" + version)
			.append(" sign=" + sign)
			.append(" order_id=" + order_id)
			.append(" refund_fee=" + refund_fee)
			.append(" comment=" + comment)
			.append(" operator_id=" + operator_id)
			.append(" operator_name=" + operator_name);
		if (logger.isInfoEnabled()) {
			logger.info("申请退款接口:" + sb);
		}
		// 1. 验证内容
		if (StringUtil.isEmpty(module_id) || module_id.length() != 6) {
			String errorMsg = Constant.RESP_STAT_MSG_0001 + ",请求模块编号错误";
			return CommonResponse.formatErrorResult(Constant.RESP_STAT_CODE_0001,errorMsg);
		}
		if (StringUtil.isEmpty(order_id)) {
			String errorMsg = Constant.RESP_STAT_MSG_0001 + ",订单编号错误";
			return CommonResponse.formatErrorResult(Constant.RESP_STAT_CODE_0001,errorMsg);
		}
		if (StringUtil.isEmpty(refund_fee) || StringUtil.isNotNum(refund_fee) || Integer.parseInt(refund_fee) <= 0) {
			String errorMsg = Constant.RESP_STAT_MSG_0001 + ",退款金额错误";
			return CommonResponse.formatErrorResult(Constant.RESP_STAT_CODE_0001,errorMsg);
		}
		
		// 2. TODO:验证模块签名
		// module_id/module_key
		
		Map<String, Object> map = new HashMap<>();
		try {
			// 3. 验证申请退款业务
			// 3.1 验证申请退款金额
			/** 目前不管申请退多少金额，都是全额退款 */
			// 3.2 验证订单号
			OrderDataEntity orderData = new OrderDataEntity();
			orderData =	iOrderDataDao.selectByPrimaryKey(order_id);
			if (orderData == null) {
				return CommonResponse.formatErrorResult(Constant.RESP_STAT_CODE_0008,Constant.RESP_STAT_MSG_0008);
			}
			List<PaymentDataEntity> paymentDatas = new ArrayList<PaymentDataEntity>();
			// 3.3 验证支付记录 已支付成功的 支付记录
			PaymentDataEntity entity = new PaymentDataEntity();
			entity.setOrdSysId(order_id);
			entity.setPayMthd(Constant.PAY_METHOD_0001);
			entity.setPayStat(Constant.PAY_STAT_CODE_SUCCESS);
			paymentDatas = iPaymentDataDao.listByEntity(entity);
			if (paymentDatas == null) {
				return CommonResponse.formatErrorResult(Constant.RESP_STAT_CODE_0009,Constant.RESP_STAT_MSG_0009);
			}
			//去掉已经退了款的记录
			List<PaymentDataEntity> paymentDatas1 = new ArrayList<>();
			for (PaymentDataEntity pay : paymentDatas) {
				if (!Constant.REFUND_STAT_CODE_SUCCESS.equals(pay.getRefundStat())) {
					paymentDatas1.add(pay);
				}
			}
			paymentDatas = paymentDatas1;
			
			// 3.4 验证支付记录 已支付成功，但未退款的记录
			if (paymentDatas.size() <= 0) {
				return CommonResponse.formatErrorResult(Constant.RESP_STAT_CODE_0009,Constant.RESP_STAT_MSG_0009);
			} else {
				for (PaymentDataEntity pay : paymentDatas) {
					logger.info("支付成功，但未退款的记录:"+ pay.getId());
				}
				// 4.1 修改订单状态 申请退款
				OrderDataEntity orderdata = new OrderDataEntity();
				orderdata.setId(order_id);
				orderdata.setRefundStat(Constant.ORD_REFUND_STAT_CODE_APPLIED);
				orderdata.setRefundStartTime(TimeUtil.getTime());
				iOrderDataDao.update(orderdata);
				// 4.2 修改所有支付记录状态 申请退款
				for (PaymentDataEntity pay : paymentDatas) {
					// 4.3每条交易记录对应一条新增的退款状态记录 Constant.PAY_METHOD_0002
					// 如果已经申请过了，不再新增一条，更新原来的申请记录
					String refundSeq = pay.getRefundSeq();//支付记录中对应退款记录的ID
					PaymentDataEntity oldRefundPay = iPaymentDataDao.selectByPrimaryKey(refundSeq);
					if (pay.getRefundSeq() != null && oldRefundPay != null) {//条件成立说明，已经申请过退款
						oldRefundPay.setApplyOperatorId(operator_id);//当前操作员
						oldRefundPay.setApplyOperatorName(operator_name);
						oldRefundPay.setApplyTime(TimeUtil.getTime());
						oldRefundPay.setApplyComment(comment);
						oldRefundPay.setRefundStat(Constant.REFUND_STAT_CODE_APPLIED);
						logger.info("支付记录"+pay.getId()+"已申请过退款"+oldRefundPay.getId());
						iPaymentDataDao.update(oldRefundPay);
					} else {
						PaymentDataEntity newRefundPay = new PaymentDataEntity();//原支付数据更新到退款数据
						BeanUtils.copyProperties(newRefundPay, pay);
						newRefundPay.setId(IdGenerator.getId());
						newRefundPay.setPayMthd(Constant.PAY_METHOD_0002);//记录类型为退款
						newRefundPay.setRefundStat(Constant.REFUND_STAT_CODE_APPLIED);
						newRefundPay.setApplyOperatorId(operator_id);//当前操作员
						newRefundPay.setApplyOperatorName(operator_name);
						newRefundPay.setApplyTime(TimeUtil.getTime());
						newRefundPay.setApplyComment(comment);
						logger.info("支付记录"+pay.getId()+"对应生成的退款记录"+newRefundPay.getId());
						iPaymentDataDao.insert(newRefundPay);
						
						pay.setRefundSeq(newRefundPay.getId());//对应退款记录字段
					}
					pay.setRefundStat(Constant.REFUND_STAT_CODE_APPLIED);
					iPaymentDataDao.update(pay);
				}
				map.put(Constant.RESP_PARAM_STAT, Constant.RESP_STAT_CODE_0000);
				map.put(Constant.RESP_PARAM_MSG, Constant.RESP_STAT_MSG_0000);
				map.put(Constant.RESP_PARAM_SIGN, "transSystem_createRefund_sign");
			}
		} catch (Exception e) {
			logger.error(this, e);
			return CommonResponse.formatErrorResult(Constant.RESP_STAT_CODE_9999, Constant.RESP_STAT_MSG_9999);
		}
		return map;
	}
	
}
